#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QFile>
#include <QDateTime>
#include <string.h>
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    socket = new QTcpSocket;
    //定时器的功能
/*//    timer = new QTimer;
    connect(timer,SIGNAL(timeout()),this,SLOT(time_out()));
    timer->start()*/;
    ui->groupBox->setVisible(false);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::ready_read()
{
    char buf[255] = {};
    char buf1[255] = "*1*2+3=4-9(!@#$)!@#$%^&*()_+";
    char buf2[255] = "*1*2+3=4-9(!@#$$$$$)!@#$%^&*()_+";
    socket->read(buf,sizeof(buf));
    if(strcmp(buf,buf1) != 0)
    {
        if(strcmp(buf,buf2) != 0)
        {
            ui->read_listWidget->addItem(buf);
        }
    }


    if(strcmp(buf,buf1) == 0)
    {
        ui->lineEdit->setEnabled(false);
        ui->send_btn->setEnabled(false);
    }
    if(strcmp(buf,buf2) == 0)
    {
        ui->lineEdit->setEnabled(true);
        ui->send_btn->setEnabled(true);
    }

}
//
void MainWindow::on_send_btn_clicked()
{
    QString buf ;
    QString buf1 = ":";
    QString buf_sum;
    QDateTime current_date_time = QDateTime::currentDateTime();
    QString current_date = current_date_time.toString(" yyyy-MM-dd hh:mm:ss ddd");

    buf = ui->name->text() + buf1;
    ui->name->setEnabled(false);
    buf_sum = buf + ui->lineEdit->text() + "  " + current_date;
    socket->write(buf_sum.toStdString().c_str(),buf_sum.toAscii().length());
    ui->lineEdit->setText("");
}

//连接到主机
void MainWindow::on_conncet_buf_clicked()
{
    socket->connectToHost(ui->lineEdit_2->text(),ui->lineEdit_3->text().toUInt());
    connect(socket,SIGNAL(readyRead()),this,SLOT(ready_read()));
}

//显示历史信息
void MainWindow::on_search_btn_clicked()
{
    QFile file("/home/zhizhen/msg.txt");
    if(!file.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        qDebug("Open failed.");
        exit(0);
    }

    QTextStream txtInput(&file);
    QString lineStr;
    while(!txtInput.atEnd())
    {
        lineStr = txtInput.readLine();
       ui->store_listWidget->addItem(lineStr);
//        vec.push_back(lineStr);
    }


    QString buf("-----------------以上是历史聊天记录----------------------");
    ui->store_listWidget->addItem(buf);
    file.close();
}


//更改姓名
void MainWindow::on_pushButton_clicked()
{
    ui->name->setEnabled(true);
}

//跳转到游戏界面
void MainWindow::on_ganme_pushButton_clicked()
{
    new_win = new new_window;
    new_win->show();
}

void MainWindow::on_commandLinkButton_clicked()
{
    ui->commandLinkButton->hide();
    ui->groupBox->show();
}

void MainWindow::on_pushButton_2_clicked()
{
    ui->groupBox->hide();
    ui->commandLinkButton->show();
}

void MainWindow::on_pushButton_3_clicked()
{
    this->close();
}

void MainWindow::on_pushButton_4_clicked()
{
    socket->close();
    ui->lineEdit_2->setText("");
    ui->lineEdit_3->setText("");
}
